package Merlion.MRP.bean;

import Merlion.MRP.entity.BillOfMaterialsEntity;
import Merlion.MRP.entity.BillOfMaterialsEntryEntity;
import Merlion.MRP.entity.IndividualWeeklyMaterialRequirementEntity;
import Merlion.MRP.entity.WeeklyMaterialRequirementEntity;
import Merlion.MRP.entity.PlannedWeeklyDemandEntity;
import Merlion.MRP.entity.UnplannedDailyDemandEntity;
import Merlion.MRP.entity.UnplannedMaterialRequirementEntity;
import Merlion.SCM.entity.MaterialEntity;
import Merlion.SCM.entity.ProductEntity;
import Merlion.util.state.MaterialRequirementState;
import java.util.ArrayList;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import Merlion.util.state.BOMEntryState;
import Merlion.util.state.BillOfMaterialState;
import Merlion.util.state.IndividualWeeklyRequirementState;
import Merlion.util.state.MRPRecordState;
import Merlion.util.state.WeeklyRequirementBreakdownState;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.persistence.Query;

@Stateless
public class MaterialManagementBean implements MaterialManagementBeanRemote {

    @PersistenceContext
    EntityManager em;
    String message;
    @EJB
    DemandManagementBeanRemote dmb;

    @Override
    public String createWeeklyMaterialRequirementByProduct(String pwdId, Date requestedOn) {
        System.out.println("Creating weekly material requirement by product");
        PlannedWeeklyDemandEntity pwd = em.find(PlannedWeeklyDemandEntity.class, pwdId);

        if (pwd == null) {
            throw new NullPointerException();
        }
        String id = pwd.getId().replaceAll("PWD", "WMR");
        WeeklyMaterialRequirementEntity wmr = em.find(WeeklyMaterialRequirementEntity.class, id);

        if (wmr == null) {
            wmr = new WeeklyMaterialRequirementEntity(pwd);
            em.persist(wmr);
        }
        wmr.setRequestedOn(requestedOn);
        wmr.setProduct(pwd.getProduct());
        pwd.setMaterialWeeklyRequirement(wmr);

        em.flush();
        System.out.println("wmr.toString() is successfully created with BOM Multiplier " + wmr.getAdjustedMultiplier());
        return wmr.getId();
    }

    @Override
    public void updateWeeklyMaterialRequirementByProduct(String wmrId, String remarks, String status, Double BOMmultiplier) {
        WeeklyMaterialRequirementEntity wmr = em.find(WeeklyMaterialRequirementEntity.class, wmrId);

        if (wmr == null) {
            throw new NullPointerException();
        }

        wmr.setRemarks(remarks);
        wmr.setStatus(status);
        wmr.setBomMultiplier(BOMmultiplier);

        em.flush();
    }

    @Override
    public void deleteWeeklyMaterialRequirementByProduct(String wmrId) {
        WeeklyMaterialRequirementEntity wmr = em.find(WeeklyMaterialRequirementEntity.class, wmrId);

        if (wmr == null) {
            throw new NullPointerException();
        }

        if (wmr.isPurchased()) {
            throw new IllegalStateException("Unable to delete requirement. Materials have already been purchased.");
        }

        em.remove(wmr);
        em.flush();
    }

    private IndividualWeeklyMaterialRequirementEntity getIndividualWeeklyMaterialRequirementEntity(WeeklyMaterialRequirementEntity wmr, MaterialEntity material) {
        String idString = "IMR" + material.getId().toString() + "-Y" + wmr.getYearInt() + "M" + wmr.getMonthInt() + "W" + wmr.getWeekOfMonth();

        IndividualWeeklyMaterialRequirementEntity imr = em.find(IndividualWeeklyMaterialRequirementEntity.class, idString);

        return imr;

    }

    private IndividualWeeklyMaterialRequirementEntity getIndividualWeeklyMaterialRequirementEntity(Long materialId, Integer yearInt, Integer monthInt, Integer weekOfMonth) {
        String idString = "IMR" + materialId.toString() + "-Y" + yearInt.toString() + "M" + monthInt.toString() + "W" + weekOfMonth.toString();

        IndividualWeeklyMaterialRequirementEntity imr = em.find(IndividualWeeklyMaterialRequirementEntity.class, idString);

        return imr;

    }

    @Override
    public void generateIndividualWeeklyMaterialRequirement(String weeklyMaterialRequirementId) {
        System.out.println("Generating/Updating individual weekly material requirement");
        WeeklyMaterialRequirementEntity wmr = em.find(WeeklyMaterialRequirementEntity.class, weeklyMaterialRequirementId);

        if (wmr == null) {
            throw new NullPointerException("Invalid ID specified");
        }

        if (wmr.isRaised()) {
            //throw new IllegalStateException("Operation aborted. Individual Weekly Material Requirements have been raised previously.");
            return;
        }

        BillOfMaterialsEntity bom = wmr.getProduct().getBOMEntity();
        for (BillOfMaterialsEntryEntity entry : bom.getEntries()) {
            System.out.println("Updating requirements of material: " + entry.getIngredient().getName());
            MaterialEntity material = entry.getIngredient();
            int quantity = (int) (wmr.getAdjustedMultiplier() * entry.getQuantity() + 0.5);
            IndividualWeeklyMaterialRequirementEntity imr = this.getIndividualWeeklyMaterialRequirementEntity(wmr, material);
            List<WeeklyMaterialRequirementEntity> wmrs = new ArrayList<WeeklyMaterialRequirementEntity>();
            if (imr == null) {
                imr = new IndividualWeeklyMaterialRequirementEntity(wmr, material, quantity);
                em.persist(imr);
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.YEAR, wmr.getYearInt());
                cal.set(Calendar.MONTH, wmr.getMonthInt() - 1);
                cal.set(Calendar.WEEK_OF_MONTH, wmr.getWeekOfMonth() - 1);
                cal.setFirstDayOfWeek(Calendar.MONDAY);
                cal.setMinimalDaysInFirstWeek(1);
                Date requestDate = cal.getTime();
                imr.setRequestedOn(requestDate);
                cal.add(Calendar.WEEK_OF_MONTH, material.getLeadTime());
                Date availabilityDate = cal.getTime();
                imr.setAvailableBy(availabilityDate);
                wmrs.add(wmr);
                em.flush();
            } else {
                wmrs = (List<WeeklyMaterialRequirementEntity>) imr.getWeeklyProductRequirements();
                if (!wmrs.contains(wmr)) {
                    imr.setRequiredAmount(imr.getRequiredAmount() + quantity);
                    wmrs.add(wmr);
                    em.flush();
                }
            }
            imr.setUnit(material.getLotSizeUnit());
            System.out.println("Associating " + wmr.toString() + "to " + imr.toString());
            imr.setWeeklyProductRequirements(wmrs);
            wmr.setRaised(true);
            em.flush();
            System.out.println("Finished updating this material");
        }
        System.out.println("Individual material requirements generated/updated");

        em.flush();
    }

    @Override
    public void updateIndividualWeeklyMaterialRequirement(String id, int requiredAmount, String status, String remarks) {
        IndividualWeeklyMaterialRequirementEntity imr = em.find(IndividualWeeklyMaterialRequirementEntity.class, id);

        if (imr == null) {
            throw new NullPointerException();
        }

        imr.setRequiredAmount(requiredAmount);
        imr.setStatus(status);
        imr.setRemarks(remarks);

        em.flush();

    }

    @Override
    public UnplannedMaterialRequirementEntity createUnplannedMaterialRequirement(Long unplannedDailyDemandId, Date requestedOn, String remarks, String status) {
        UnplannedDailyDemandEntity udd = em.find(UnplannedDailyDemandEntity.class, unplannedDailyDemandId);

        if (udd == null) {
            throw new NullPointerException();
        }

        WeeklyMaterialRequirementEntity wmr = udd.getPlannedDailyDemandEntity().getPlannedWeeklyDemand().getMaterialWeeklyRequirement();
        UnplannedMaterialRequirementEntity umr = new UnplannedMaterialRequirementEntity(udd, wmr);
        em.persist(umr);

        umr.setRequestedOn(requestedOn);
        umr.setRemarks(remarks);
        umr.setStatus(status);

        udd.setUnplannedMaterialRequirementEntity(umr);
        List<UnplannedMaterialRequirementEntity> umrs = new ArrayList();
        umrs = (List<UnplannedMaterialRequirementEntity>) wmr.getUnplannedMaterialRequirementEntities();
        umrs.add(umr);
        wmr.setUnplannedMaterialRequirementEntities(umrs);
        wmr.setAdjustedMultiplier(wmr.getBomMultiplier() + umr.getBomMultiplier());
        em.flush();

        return umr;

    }

    @Override
    public void deleteUnplannedMaterialRequirement(Long id) {
        UnplannedMaterialRequirementEntity umr = em.find(UnplannedMaterialRequirementEntity.class, id);

        if (umr == null) {
            throw new NullPointerException();
        }

        if (umr.isPurchased()) {
            throw new IllegalStateException("Unable to delete requirement. Materials have already been purchased.");
        }

        UnplannedDailyDemandEntity udd = umr.getUnplannedDailyDemand();
        WeeklyMaterialRequirementEntity wmr = umr.getWeeklyMaterialRequirement();

        udd.setUnplannedMaterialRequirementEntity(null);
        udd.setProcured(false);

        List<UnplannedMaterialRequirementEntity> umrs = new ArrayList();
        umrs = (List<UnplannedMaterialRequirementEntity>) wmr.getUnplannedMaterialRequirementEntities();
        umrs.remove(umr);
        wmr.setUnplannedMaterialRequirementEntities(umrs);

        umr.setWithdrawn(true);
        em.flush();
    }

    @Override
    public void createBOMEntry(Long productId, Long ingredientId, double quantity, String unit) {

        em.clear();
        ProductEntity product = em.find(ProductEntity.class, productId);
        MaterialEntity ingredient = em.find(MaterialEntity.class, ingredientId);

        if (product == null || ingredient == null) {
            throw new NullPointerException("No such product");
        }
        System.out.println("Creating BOM entry for " + ingredient.getName() + " to " + product.getName());
        BillOfMaterialsEntity BOM = product.getBOMEntity();

        if (BOM == null) {
            BOM = new BillOfMaterialsEntity(product);
            em.persist(BOM);
            product.setBOMEntity(BOM);
            em.flush();
        }

        Long entryId = this.getBOMEntryId(BOM, ingredient);
        if (entryId != null) {
            this.updateBOMEntry(entryId, ingredientId, quantity, unit);
            System.out.println("Material has been previously assigned to the BOM, update operation took place instead");
            return;
        }
        System.out.println("Creating new BOM entry for " + ingredient.getName());
        BillOfMaterialsEntryEntity entry = new BillOfMaterialsEntryEntity();
        entry.setBOMEntity(BOM);
        entry.setIngredient(ingredient);
        entry.setQuantity(quantity);
        entry.setUnit(unit);
        em.persist(entry);
        System.out.println("bom entry persisted");

        List<BillOfMaterialsEntryEntity> entries = new ArrayList();
        entries = (List<BillOfMaterialsEntryEntity>) BOM.getEntries();

        entries.add(entry);
        BOM.setEntries(entries);
        em.flush();
        System.out.println("bom entry successfully updated");

    }

    @Override
    public void deleteBOMEntry(Long entryId) {

        BillOfMaterialsEntryEntity entry = em.find(BillOfMaterialsEntryEntity.class, entryId);
        if (entry == null) {
            throw new NullPointerException("No such entry");
        }

        BillOfMaterialsEntity BOM = entry.getBOMEntity();

        List<BillOfMaterialsEntryEntity> entries = new ArrayList();
        entries = (List<BillOfMaterialsEntryEntity>) BOM.getEntries();

        entries.remove(entry);
        BOM.setEntries(entries);
        entry.setBOMEntity(null);
        em.remove(entry);
        em.flush();


    }

    @Override
    public void updateBOMEntry(Long entryId, Long ingredientId, double quantity, String unit) {


        BillOfMaterialsEntryEntity entry = em.find(BillOfMaterialsEntryEntity.class, entryId);
        if (entry == null) {
            throw new NullPointerException("No such entry");
        }

        MaterialEntity ingredient = em.find(MaterialEntity.class, ingredientId);
        if (ingredient == null) {
            throw new NullPointerException("No such ingredient");
        }

        entry.setIngredient(ingredient);
        entry.setQuantity(quantity);
        entry.setUnit(unit);
        em.flush();
    }

    @Override
    public void createBillOfMaterial(Long productId, int batchSize, String unit) {
        ProductEntity product = em.find(ProductEntity.class, productId);
        if (product == null) {
            throw new NullPointerException("No such product");
        }

        BillOfMaterialsEntity BOM = product.getBOMEntity();

        if (BOM != null) {
            this.updateBillOfMaterial(productId, batchSize, unit);
        }

        BOM = new BillOfMaterialsEntity(product);
        em.persist(BOM);
        product.setBOMEntity(BOM);
        BOM.setBatchSize(batchSize);
        BOM.setBatchUnit(unit);
        em.flush();
    }

    @Override
    public void updateBillOfMaterial(Long productId, int batchSize, String unit) {
        System.out.println("MaterialManagementBean : updateBillOfMaterial()");
        ProductEntity product = em.find(ProductEntity.class, productId);
        if (product == null) {
            throw new NullPointerException("No such product");
        }

        BillOfMaterialsEntity BOM = product.getBOMEntity();

        if (BOM == null) {
            throw new NullPointerException("Bill of Material has not been created for the product");
        }

        BOM.setBatchSize(batchSize);
        BOM.setBatchUnit(unit);
        em.merge(BOM);
        em.flush();

        System.out.println("BOM BATCH SIZE= " + BOM.getBatchSize());
    }

    @Override
    public void deleteBillOfMaterial(Long productId) {
        ProductEntity product = em.find(ProductEntity.class, productId);
        if (product == null) {
            throw new NullPointerException("No such product");
        }

        BillOfMaterialsEntity BOM = product.getBOMEntity();

        if (BOM == null) {
            throw new NullPointerException("Bill of Material has not been created for the product");
        }

        List<BillOfMaterialsEntryEntity> entries = new ArrayList();
        entries = (List<BillOfMaterialsEntryEntity>) BOM.getEntries();

        for (BillOfMaterialsEntryEntity entry : entries) {
            System.out.println("Removing Bill of Material entry: " + entry.toString());
            entry.setBOMEntity(null);
            em.remove(entry);
        }
        entries.clear();
        BOM.setEntries(entries);
        product.setBOMEntity(null);
        em.remove(BOM);
        em.flush();
        System.out.println(BOM.toString() + " successfully removed.");

    }

    private Long getBOMEntryId(BillOfMaterialsEntity bom, MaterialEntity material) {
        System.out.println("Private: Getting BOM Entry Id..");
        List<BillOfMaterialsEntryEntity> entries = new ArrayList();
        entries = (List<BillOfMaterialsEntryEntity>) bom.getEntries();

        for (BillOfMaterialsEntryEntity entry : entries) {
            if (entry.getIngredient().getId().equals(material.getId())) {
                System.out.println("BOM entry existed for material: " + material.getName() + " with id: " + entry.getId());
                return entry.getId();
            }
        }

        return null;
    }

    @Override
    public BillOfMaterialState viewProductBillOfMaterial(Long productId) {
        ProductEntity product = em.find(ProductEntity.class, productId);
        if (product == null) {
            throw new NullPointerException("No such product");
        }

        BillOfMaterialsEntity BOM = product.getBOMEntity();

        if (BOM == null) {
            throw new NullPointerException("Bill of Material has not been created for the product");
        }

        BillOfMaterialState BOMState = new BillOfMaterialState(BOM.getId(), productId, product.getName(), BOM.getBatchSize(), BOM.getBatchUnit());

        List<BOMEntryState> eStates = new ArrayList();
        for (BillOfMaterialsEntryEntity entry : BOM.getEntries()) {
            BOMEntryState eState = new BOMEntryState(entry.getId(), entry.getIngredient().getId(), entry.getIngredient().getName(), entry.getQuantity(), entry.getUnit());
            eStates.add(eState);
        }

        BOMState.setEntries(eStates);

        return BOMState;
    }

    @Override
    public List<MaterialRequirementState> viewMaterialRequirementByWeekOfMonth(Integer yearInt, Integer monthInt, Integer weekOfMonth) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public MRPRecordState viewMRPRecord(Long materialId, Integer yearInt, Integer monthInt) {
        System.out.println("Generating MRP Record");
        MaterialEntity material = em.find(MaterialEntity.class, materialId);

        Integer getYearInt = yearInt;
        Integer getMonthInt = monthInt;
        int beginningInventory;
        if (monthInt.intValue() == 1) {
            getYearInt = yearInt - 1;
            getMonthInt = 12;
        } else {
            getMonthInt--;
        }
        IndividualWeeklyMaterialRequirementEntity lastimr = this.getIndividualWeeklyMaterialRequirementEntity(materialId, getYearInt, getMonthInt, (Integer) 6);
        if (lastimr != null) {
            beginningInventory = lastimr.getInHandInventory();
        } else {
            beginningInventory = 500;
        }
        int leadtime = material.getLeadTime();
        MRPRecordState mrpState = new MRPRecordState(yearInt, monthInt, materialId, material.getName(), beginningInventory, leadtime);
        List<IndividualWeeklyRequirementState> imrStates = new ArrayList();
        int[] grossRequirements = new int[6];
        int[] scheduledReceipts = new int[6];
        int[] plannedReceipts = new int[6];
        int[] inHandInventories = new int[6];
        int[] plannedOrders = new int[6];
        int shortage = beginningInventory * -1;
        Query q = em.createQuery("SELECT a from IndividualWeeklyMaterialRequirementEntity a WHERE a.yearInt = :yearInt AND a.monthInt = :monthInt ORDER BY a.weekOfMonth").setParameter("yearInt", yearInt).setParameter("monthInt", monthInt);
        List<IndividualWeeklyMaterialRequirementEntity> imrs = new ArrayList();
        for (Object o : q.getResultList()) {
            IndividualWeeklyMaterialRequirementEntity imr = (IndividualWeeklyMaterialRequirementEntity) o;
            if (imr.getMaterial().getId().compareTo(materialId) == 0) {
                imrs.add(imr);
                System.out.println("Fetching " + imr.toString());
            }
        }
        for (IndividualWeeklyMaterialRequirementEntity imr : imrs) {
            System.out.println("Calculating total gross requirement for the month");
            int grossRequirement = 0;
            Integer weekInt = imr.getWeekOfMonth();
            List<WeeklyMaterialRequirementEntity> wmrs = new ArrayList();
            wmrs = (List<WeeklyMaterialRequirementEntity>) imr.getWeeklyProductRequirements();

            for (WeeklyMaterialRequirementEntity wmr : wmrs) {
                ProductEntity product = wmr.getProduct();
                BillOfMaterialsEntity bom = product.getBOMEntity();
                Long bomEntryId = this.getBOMEntryId(bom, material);
                System.out.println("The BOM Entry Id for this material requirement mapping is: " + bomEntryId);
                BillOfMaterialsEntryEntity bomEntry = em.find(BillOfMaterialsEntryEntity.class, bomEntryId);
                double requirementPerBatch = bomEntry.getQuantity();
                int requiredCase = wmr.getPlannedWeeklyDemand().getWeeklyDemand();
                int requiredUnitBatch = (int) ((requiredCase * product.getCaseWeight() / product.getBOMEntity().getBatchSize()) + 0.5);
                grossRequirement += (int) (requiredUnitBatch * requirementPerBatch + 0.5);
                em.detach(product);
                em.detach(bom);
                em.detach(bomEntry);
            }
            grossRequirements[weekInt - 1] = grossRequirement;
            shortage += grossRequirement;
            System.out.println("Total amount of required materials for the month: " + shortage);
        }

        int divisor;
        if (grossRequirements[5] == 0) {
            divisor = 5;
        } else {
            divisor = 6;
        }
        int floor = 300;
        int plannedReceipt = (int) Math.round(((double) (shortage + floor) / divisor + 50) / 100) * 100;
        plannedReceipts[0] = plannedReceipt;
        inHandInventories[0] = beginningInventory + plannedReceipts[0] - grossRequirements[0];
        for (int k = 0; k < 6; k++) {
            int j = k + 1;
            if (j < 6) {
                System.out.println("Gross Requirement for week " + (j + 1) + " is " + grossRequirements[j]);
                plannedReceipts[j] = plannedReceipt;
                if (divisor == 5 && j == 5) {
                    plannedReceipts[j] = 0;
                }
                inHandInventories[j] = inHandInventories[j - 1] + plannedReceipts[j] - grossRequirements[j];
            }
            while (inHandInventories[k] > floor && k < 5) { // ensuring lean operation
                if (plannedReceipts[k] <= 0) { // plannedReceipt > 0
                    break;
                }
                inHandInventories[k] -= 100;
                plannedReceipts[k] -= 100;
                plannedReceipts[k + 1] += 100;

            }

            while (inHandInventories[k] < floor && k < 5) { // ensuring capacity
                if (plannedReceipts[k + 1] <= 0) { // plannedReceipt > 0
                    break;
                }
                inHandInventories[k] += 100;
                plannedReceipts[k] += 100;
                plannedReceipts[k + 1] -= 100;

            }

            if (k >= leadtime) {
                plannedOrders[k - leadtime] = plannedReceipts[k];
            }

            if (k < leadtime) {
                scheduledReceipts[k] = plannedReceipts[k];
                plannedReceipts[k] = 0;
            }
        }

        for (IndividualWeeklyMaterialRequirementEntity imr : imrs) {
            System.out.println("Setting up the helper states");
            Integer weekInt = imr.getWeekOfMonth();
            int requiredTotalCase = 0;
            int requiredTotalUnitBatch = 0;
            int grossRequirement = 0;
            List<WeeklyMaterialRequirementEntity> wmrs = new ArrayList();
            wmrs = (List<WeeklyMaterialRequirementEntity>) imr.getWeeklyProductRequirements();
            List<WeeklyRequirementBreakdownState> breakdowns = new ArrayList();


            for (WeeklyMaterialRequirementEntity wmr : wmrs) {
                ProductEntity product = wmr.getProduct();
                BillOfMaterialsEntity bom = product.getBOMEntity();
                Long bomEntryId = this.getBOMEntryId(bom, material);
                BillOfMaterialsEntryEntity bomEntry = em.find(BillOfMaterialsEntryEntity.class, bomEntryId);
                double requirementPerBatch = bomEntry.getQuantity();
                int requiredCase = wmr.getPlannedWeeklyDemand().getWeeklyDemand();
                requiredTotalCase += requiredCase;
                int requiredUnitBatch = (int) ((requiredCase * product.getCaseWeight() / product.getBOMEntity().getBatchSize()) + 0.5);
                requiredTotalUnitBatch += requiredUnitBatch;
                grossRequirement += (int) (requiredUnitBatch * requirementPerBatch + 0.5);
                WeeklyRequirementBreakdownState breakdown = new WeeklyRequirementBreakdownState(wmr.getProduct().getId(), wmr.getProduct().getName(), requiredCase, requiredUnitBatch);
                breakdowns.add(breakdown);
            }
            /*if (!imr.isPurchased()) */ { 
                IndividualWeeklyRequirementState imrState = new IndividualWeeklyRequirementState(weekInt, requiredTotalCase, requiredTotalUnitBatch, grossRequirement, plannedReceipts[weekInt - 1], inHandInventories[weekInt - 1], plannedOrders[weekInt - 1]);
                imrState.setScheduledReceipt(scheduledReceipts[weekInt - 1]);
                imr.setInHandInventory(inHandInventories[weekInt - 1]);
                if (plannedReceipts[weekInt - 1] != 0) {
                    imr.setPlannedReceipt(plannedReceipts[weekInt - 1]);
                } else {
                    imr.setPlannedReceipt(scheduledReceipts[weekInt - 1]);
                }
                imr.setRequiredAmount(grossRequirement);
                imr.setPlannedOrder(plannedOrders[weekInt - 1]);
                em.flush();
                imrState.setBreakdowns(breakdowns);
                System.out.println("Individual Breakdowns set");
                imrStates.add(imrState);
            } /*else {
            int inHandInventory = inHandInventories[weekInt - 2] + imr.getPlannedReceipt() - imr.getRequiredAmount();
            IndividualWeeklyRequirementState imrState = new IndividualWeeklyRequirementState(weekInt, requiredTotalCase, requiredTotalUnitBatch, imr.getRequiredAmount(), imr.getPlannedReceipt(), inHandInventory, imr.getPlannedOrder());
            imrState.setPurchased(true);
            imrStates.add(imrState);
            }*/
        }
        /*
        int floor = 200;
        int supply, demand, glut, leastGlut;
        leastGlut = 0;
        while (leastGlut < floor) {
        leastGlut = 199;
        for (int k = 5; k >= leadtime; k--) {
        supply = inHandInventories[k-1] + plannedReceipts[k];
        demand = grossRequirements[k];
        glut = supply - demand;
        int shortage = glut * -1;
        plannedReceipts[k] = (int) Math.round(((double)shortage + (double)floor + 50)/100) * 100;
        plannedOrders[k-leadtime] = plannedReceipts[k];
        inHandInventories[k-1] = grossRequirements[k] + inHandInventories[k] - plannedReceipts[k];
        if (glut < leastGlut) {
        leastGlut = glut;
        }
        }
        
        supply = beginningInventory;
        for (int k = 0; k < leadtime; k++) {
        supply += plannedReceipts[k];
        demand = grossRequirements[k];
        shortage = demand - supply;
        }
        }
         */
        mrpState.setWeeklyMaterialStates(imrStates);
        System.out.println("Weekly Material States set");
        return mrpState;
    }

    public String getLotSizeUnit(Long materialId) {
        System.out.println("**MaterialManagementBean: getLotSizeUnit()");

        MaterialEntity material = em.find(MaterialEntity.class, materialId);
        String unit = material.getLotSizeUnit();

        return unit;
    }
}
